<?php


namespace App\Http\Controllers\applets\service;


use App\Http\Controllers\applets\model\AdminAppModel;
use App\Http\Controllers\applets\model\AdminModel;
use App\Http\Controllers\applets\model\AppInstallModel;
use App\Http\Controllers\applets\model\AppLogModel;
use App\Http\Controllers\applets\model\GroupModel;
use App\Http\Controllers\applets\model\ParentAppModel;
use App\Http\Controllers\applets\model\ParentSnModel;
use App\Http\Controllers\applets\model\SubjectModel;
use App\Http\Controllers\applets\model\SysAppModel;
use App\Http\Controllers\applets\model\TeacherAppModel;
use App\Http\Controllers\utils\LogUtil;
use App\Http\Controllers\utils\ToolUtil;
use Illuminate\Support\Facades\DB;

class AppService
{
    /**
     * 获取科目信息
     * @param $param
     * @return false|string
     */
    public static function getSubject($param){
        $where = [];
        if(isset($param['sId']) && !empty($param['sId'])){
            $sn_grade_name = DB::table('t_parent_sn as p')
                ->leftJoin('t_sn_grade as s','p.sn_grade_id','=','s.id')
                ->where('p.id',$param['sId'])->value('s.class_name');
            $preschool = ['大班','中班','小班'];
            $primarySchool = ['一年级','二年级','三年级','四年级','五年级','六年级'];
            $jMiddleSchool = ['初一','初二','初三'];
            if(in_array($sn_grade_name,$preschool)){
                $where['grade_id'] = DB::table('t_grade')->where(['title'=>'学前班'])->value('id');
            }elseif (in_array($sn_grade_name,$primarySchool)){
                $where['grade_id'] = DB::table('t_grade')->where(['title'=>'小学'])->value('id');
            }elseif(in_array($sn_grade_name,$jMiddleSchool)){
                $where['grade_id'] = DB::table('t_grade')->where(['title'=>'中学'])->value('id');
            }
        }
        $data = DB::table('t_subject')->where($where)->get(['id','name']);
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 获取应用信息详情
     * @param $param
     * @return false|string
     */
    public static function getAdminAppDetails($param){

        $id = (int)$param['id'];
        $field = ['a.id','a.app_name','a.app_package','a.app_size','a.app_img','g.title','s.name','a.app_downloads','a.top_search','a.app_desc','a.create_time','a.app_score','a.app_preview1','a.app_remarks'];
        $data = DB::table('t_admin_app as a')
            ->leftJoin('t_grade as g','a.app_grade_id','=','g.id')
            ->leftJoin('t_subject as s','a.app_subject_id','=','s.id')
            ->where('a.id',$id)
            ->first($field);

        if(!empty($data)){

            $data['app_size'] = round($data['app_size']/1024/1024,2);
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');

    }


    /**
     * 获取应用信息
     * @param $param
     * @return false|string
     */
    public static function getAdminApp($param){
        if(empty($param['snId'])){
            return ToolUtil::returnJson(401,'设备参数为空');
        }
        switch ($param['type']){
            case 1:
                if(empty($param['id'])){
                    return ToolUtil::returnJson(401,'科目参数不存在或者为空');
                }
                $subject = SubjectModel::queryFirst(['id'=>$param['id']],['id']);
                if(!$subject){
                    return ToolUtil::returnJson(401,'不存在该科目');
                }
                $where['a.app_subject_id'] = $param['id'];
                $data = AdminAppModel::queryAll($where);
                if(count($data)){
                    $result = self::handleSize($data);
                    $result = self::isHide($result,$param);
                    return ToolUtil::returnJson(200,'成功',$result);
                }
                return ToolUtil::returnJson(400,'没有数据');
            case 2:
                if(!isset($param['appName']) && empty($param['appName'])){
                    return ToolUtil::returnJson(401,'应用名称不存在或为空');
                }
                $param['field'] = 'a.app_name';
                $param['a.app_name'] = $param['appName'];
                $where = [];
                if(!empty($param['id'])){
                    $where['a.app_subject_id'] = $param['id'];
                }
                $data = AdminAppModel::queryAll($where,$param);
                if(count($data)){
                    $result = self::handleSize($data);
                    $result = self::isHide($result,$param);
                    return ToolUtil::returnJson(200,'成功',$result);
                }
                return ToolUtil::returnJson(400,'没有数据');
            case 3:
                if(empty($param['id'])){
                    return ToolUtil::returnJson(401,'科目参数不存在或者为空');
                }
                if(!isset($param['appName']) && empty($param['appName'])){
                    return ToolUtil::returnJson(401,'应用名称不存在或为空');
                }

                $where = ['a.app_subject_id'=>$param['id']];
                $param['field'] = 'a.app_name';
                $param['a.app_name'] = $param['appName'];
                $data = AdminAppModel::queryAll($where,$param);
                if(count($data)){
                    $result = self::handleSize($data);
                    $result = self::isHide($result,$param);
                    return ToolUtil::returnJson(200,'成功',$result);
                }
                return ToolUtil::returnJson(400,'没有数据');

            default:
                return ToolUtil::returnJson(302,'类型错误');
        }
    }


    public static function handleSize($data){

        foreach ($data as $k=>$v){
            $v['app_size'] = round($v['app_size']/1024/1024,2);
        }
        return $data;
    }

    public static function isHide($data,$param){
        $sn = DB::table('t_admin_sn as a')->leftJoin('t_parent_sn as p','a.id','=','p.admin_sn_id')
            ->where('p.id',$param['snId'])->value('a.value');
        foreach ($data as $k=>$v){
            if(DB::table('t_parent_app')
                ->where(['app_package'=>$v['app_package'],'app_version_name'=>$v['app_version_name'],'sn_value'=>$sn])
                ->value('id')){
                $v['hide'] = 1;
            }else{
                $v['hide'] = 0;
            }
            $data[$k] = $v;
        }
        return $data;
    }


    /**
     * 应用市场安装
     * @param $param
     * @return false|string
     */
    public static function appInstall($param){

        return self::handleAdminApp($param,1);

    }


    /**
     * 应用市场推送
     * @param $param
     * @return false|string
     */
    public static function appPush($param){

        return self::handleAdminApp($param,0);

    }


    public static function handleAdminApp($param,$type){

        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$param['snId']],['a.value','p.teacher_id','p.admin_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(302,'该设备没有绑定');
        }
        $field = ['app_name','app_version_name','app_package','app_version_code','app_size','app_url','app_img','app_md5','app_downloads'];
        $app = AdminAppModel::queryFirst(['id'=>$param['appId']],$field);
        if(empty($app)){
            return ToolUtil::returnJson(301,'不存在该应用');
        }

        $app['is_silent'] = $type;
        $appDownloads = $app['app_downloads'];
        unset($app['app_downloads']);
        $app['admin_id'] = $parent['admin_id'];
        $app['sn_value'] = $parent['value'];
        $app['create_time'] = time();
        if($parent['teacher_id']){
            return ToolUtil::returnJson(301,'该设备已经授权给老师');
        }else{
            if(ParentAppModel::queryFirst(['sn_value'=>$parent['value'],'app_package'=>$app['app_package']],['id'])){
                return ToolUtil::returnJson(301,'设备已经有这个应用');
            }else{
                $int = ParentAppModel::add($app);
            }
        }

        if(!empty($int)){

            AdminAppModel::edit(['id'=>$param['appId']],['app_downloads'=>$appDownloads+1]);

            if($type === 1){

                $param['remark'] = '应用市场安装';
                $param['status'] = 1;
                $param['type'] = 2;
                $param['batch'] = array($parent['value']);
                $param['title'] = 'OK';
                $param['contentType'] = 9;
                $param['statusType'] = '应用市场安装';
                $jPush = LogUtil::addPushLog($param,['package'=>$app['app_package'],'url'=>$app['app_url']]);
                if(in_array(200,$jPush)){
                    
                    $param['details'] = ToolUtil::handleSuccessOrError(['code'=>'success','package'=>$app['app_package']]);
                    LogUtil::addAdminLog($param);
                    return ToolUtil::returnJson(200,'成功');
                }else{
                    $param['details'] = ToolUtil::handleSuccessOrError(['code'=>'error','package'=>$app['app_package']],0);
                    LogUtil::addAdminLog($param);
                    return ToolUtil::returnJson(301,'推送失败');
                }

            }else{

                $param['remark'] = '应用市场推送';
                $param['details'] = ToolUtil::handleSuccessOrError(['code'=>'success','package'=>$app['app_package']]);
                LogUtil::addAdminLog($param);
                return ToolUtil::returnJson(200,'成功');

            }

        }else{
            if($type === 1){
                $param['remark'] = '应用市场安装';
            }else{
                $param['remark'] = '应用市场推送';
            }
            $param['details'] = ToolUtil::handleSuccessOrError(['code'=>'error','package'=>$app['app_package']],0);
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(300,'失败');
        }

    }


    /**
     * 设备每日在线和应用使用信息
     * @param $param
     * @return false|string
     */
    public static function querySnLogInfo($param){
        $parentSn = ParentSnModel::queryWhereFirst(['p.id'=>$param['id']],['p.id','a.value','a.name','a.avatar','a.addr','a.is_wifi','a.quantity','a.minute','a.storage','a.use_space','a.use_ram','a.wifi_ssid','a.wifi_time','a.boot_time','a.devices_version','a.appstore_version','a.jiaoguanyi_version','a.orm_version','a.gankao_version','a.updatetools_version','a.info_version']);
        if($parentSn){
            $sn = [];
            $runApp = DB::table('t_run_app')->where('sn_value',$parentSn['value'])->first(['type','create_time','minute']);
            if($runApp){
                $sn['create_time'] = $runApp['create_time'];
                $sn['minute'] = $runApp['minute'];
                if($runApp['type']==1){
                    $app = DB::table('t_run_app as r')
                        ->leftJoin('t_sys_app as s','r.app_id','=','s.id')
                        ->where('r.sn_value',$parentSn['value'])->first(['s.app_package','s.app_name','s.app_img']);
                }elseif($runApp['type']==2){
                    $app = DB::table('t_run_app as r')
                        ->leftJoin('t_teacher_app as s','r.app_id','=','s.id')
                        ->where('r.sn_value',$parentSn['value'])->first(['s.app_package','s.app_name','s.app_img']);
                }elseif($runApp['type']==3){
                    $app = DB::table('t_run_app as r')
                        ->leftJoin('t_parent_app as s','r.app_id','=','s.id')
                        ->where('r.sn_value',$parentSn['value'])->first(['s.app_package','s.app_name','s.app_img']);
                }else{
                    $app = [];
                }
                if($app){
                    $sn['app_name'] = $app['app_name'];
                    $sn['app_package'] = $app['app_package'];
                    $sn['app_img'] = $app['app_img'];
                }
            }
            $install_count = AppInstallModel::queryCount(['sn_value'=>$parentSn['value']]);
            if(!empty($install_count)){
                $parentSn['install_count'] = AppInstallModel::queryCount(['sn_value'=>$parentSn['value']]);
            }else{
                $parentSn['install_count'] = 0;
            }
            
            $parentSn['app'] = $sn;
            return ToolUtil::returnJson(200,'成功',$parentSn);
        }
        return ToolUtil::returnJson(400,'没有该设备信息');
    }


    /**
     * 获取应用使用时长统计
     * @param $param
     * @return false|string
     */
    public static function getAppUseTimeLog($param){
        
        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$param['id']],['a.value','p.teacher_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(301,'该设备没有绑定');
        }

        if(empty($param['time'])){
            $time = time();
        }else{
            $time = (int)$param['time'];
        }

        $sn = $parent['value'];
        $date_str = date('Ymd',$time);

        $app = DB::table('t_app_use_info')->where(['date_str'=>$date_str,'sn'=>$sn])->orderBy('use_time', 'desc')->get(['packages','app_name','use_time']);

        if(count($app)){

            $data = [];
            foreach ($app as $key => $value) {
                
                $img = DB::table('t_sys_app')->where(['app_package'=>$value['packages']])->first(['app_img']);
                if(empty($img)){
                    $img = DB::table('t_parent_app')->where(['app_package'=>$value['packages']])->first(['app_img']);
                }
                if(empty($img)){
                    $img = DB::table('t_teacher_app')->where(['app_package'=>$value['packages']])->first(['app_img']);
                }
                if(empty($img)){
                    $img['app_img'] = '';
                }

                $data[$key]['app_name'] = $value['app_name'];
                $data[$key]['use_time'] = $value['use_time'];
                $data[$key]['app_img'] = $img['app_img'];

            }

            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }


    /**
     * 刷新
     * @param $param
     * @return false|string
     */
    public static function checkRefresh($param){
        $parentSn = ParentSnModel::queryWhereFirst(['p.id'=>$param['id']],['a.value','p.admin_id']);
        if($parentSn){
            $param['userId'] = $parentSn['admin_id'];
            $param['status'] = 1;
            $param['contentType'] = 2;
            $param['type'] = 2;
            $param['statusType'] = '刷新';
            $param['title'] = 'OK';
            $param['batch'] = array($parentSn['value']);
            $jPush = LogUtil::addPushLog($param);
            $param['status'] = 2;
            LogUtil::addPushLog($param);
            if(in_array(200,$jPush)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(200,'成功,推送失败');
        }
    }


    /**
     * 获取应用日志
     * @param $param
     * @return false|string
     */
    public static function queryAppLog($param){
        $parentSn = ParentSnModel::queryWhereFirst(['p.id'=>$param['id']],['a.value','p.teacher_id']);
        if($parentSn){
            if(isset($param['create_time']) && !empty($param['create_time'])){
                $create_time = $param['create_time'];
                $end_time = $create_time+24*60*60;
            }else{
                $create_time = strtotime(date('y-m-d',time()))-8*60*60;
                $end_time = $create_time+24*60*60;
            }
            if($parentSn['teacher_id']){
                $data = AppLogModel::queryLikeTeacher(['a.sn_value'=>$parentSn['value']],['create_time'=>$create_time,'end_time'=>$end_time]);
            }else{
                $data = AppLogModel::queryLikeParent(['a.sn_value'=>$parentSn['value']],['create_time'=>$create_time,'end_time'=>$end_time]);
            }
            if(count($data)){
                return ToolUtil::returnJson(200,'成功',$data);
            }
            return ToolUtil::returnJson(400,'没有数据');
        }
        return ToolUtil::returnJson(301,'该设备还没有进行绑定');
    }

    /**
     * 获取应用统计日志
     * @param $param
     * @return false|string
     */
    public static function querySumAppLog($param){
        return ToolUtil::returnJson(400,'已弃用');
        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$param['id']],['a.value','p.teacher_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(301,'该设备没有绑定');
        }
        if(isset($param['create_time']) && !empty($param['create_time'])){
            $create_time = $param['create_time'];
            $end_time = $create_time+24*60*60;
        }else{
            $create_time = strtotime(date('y-m-d',time()))-8*60*60;
            $end_time = $create_time+24*60*60;
        }
        if($parent['teacher_id']){
            $app = AppLogModel::queryAddLikeTeacher(['snValue'=>$parent['value']],['create_time'=>$create_time,'end_time'=>$end_time]);
        }else{
            $app = AppLogModel::queryAddLikeParent(['snValue'=>$parent['value']],['create_time'=>$create_time,'end_time'=>$end_time]);
        }
        if(count($app)){
            foreach($app as $k=>$v){
                if($parent['teacher_id']){
                    $tApp = TeacherAppModel::queryFirst(['id'=>$v['teacher_app_id']],['app_name','app_img']);
                    $v['appName'] = $tApp['app_name'];
                    $v['appUrl'] = $tApp['app_img'];
                }else{
                    $pApp= ParentAppModel::queryFirst(['id'=>$v['parent_app_id']],['app_name','app_img']);
                    $v['appName'] = $pApp['app_name'];
                    $v['appUrl'] = $pApp['app_img'];
                }
                $app[$k] = $v;
            }
            return ToolUtil::returnJson(200,'成功',$app);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }



    /**
     * 编号获取应用信息(应用管控)
     * 
     * @param $param
     * @return false|string
     */
    public static function queryIdApp($param){

        $id = (int)$param['id'];
        $field = ['id','is_lock','is_network','is_upgrade','address','visit','app_name','app_version_name','app_img','app_size'];
        $data = ParentAppModel::queryFirst(['id'=>$id],$field);

        if(!empty($data['id'])){

            $t_app_inside = DB::table('t_app_inside')->where('app_id',$id)->where('type',1)->first(['content','status']);
            if($t_app_inside){
                $data['inside_content'] = $t_app_inside['content'];
                $data['inside_status'] = $t_app_inside['status'];
            }else{
                $data['inside_content'] = '';
                $data['inside_status'] = 0;
            }

            $data['app_size'] = round($data['app_size']/1024/1024,2);
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 修改应用信息(应用管控)
     * 
     * @param $param
     * @return false|string
     */
    public static function editAppAll($param){
        try {

            if(empty($param['address'])){
                $param['address'] = '';
            }

            if(empty($param['visit'])){
                $param['visit'] = '';
            }

            $id = (int)$param['id'];
            $pdata = ParentAppModel::queryFirst(['id'=>$id],['sn_value','app_package']);

            if(!$pdata){
                return ToolUtil::returnJson(301,'没有记录');
            }

            $parent = ParentSnModel::queryWhereFirst(['a.value'=>$pdata['sn_value']],['p.teacher_id']);
            if(!$parent){
                return ToolUtil::returnJson(302,'该设备没有绑定');
            }
            if(!empty($parent['teacher_id'])){
                return ToolUtil::returnJson(303,'该设备授权老师，不能进行该操作');
            }

            $inside_status = (int)$param['inside_status'];
            if($inside_status === 1 && empty($param['inside_content'])){
                return ToolUtil::returnJson(302,'应用ID内容不能为空');
            }

            if($inside_status === 1){
                $inside_content = $param['inside_content'];
            }else{
                $inside_content = '';
                $inside_status = 0;
            }

            DB::beginTransaction();

            $t_app_inside = DB::table('t_app_inside')->where('app_id',$id)->where('type',1)->first(['content','status']);
            if($t_app_inside){

                $t_app_inside_res = DB::table('t_app_inside')->where('app_id',$id)->where('type',1)->update(['content'=>$inside_content,'status'=>$inside_status,'update_time'=>time()]);

            }else{

                if($inside_status === 1){
                    $t_app_inside_res = DB::table('t_app_inside')->insert(['sn'=>$pdata['sn_value'],'package'=>$pdata['app_package'],'app_id'=>$id,'type'=>1,'add_time'=>time(),'admin_id'=>$param['userId'],'content'=>$inside_content,'status'=>1]);
                }

            }



            $data = [
                'is_lock'=>$param['is_lock'],
                'is_network'=>$param['is_network'],
                'is_upgrade'=>$param['is_upgrade'],
                'address'=>$param['address'],
                'visit'=>$param['visit'],
                'update_time'=>time()
            ];
            
            if(ParentAppModel::edit(['id'=>$id],$data)){

                DB::commit();
                if(!empty($t_app_inside_res)){

                    $param['contentType'] = 7;
                    $param['type'] = 2;
                    $param['batch'] = array($pdata['sn_value']);
                    $param['statusType'] = '小程序应用ID管控';
                    LogUtil::addPushLog($param);
                    $param['remark'] = '小程序应用ID管控';
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$pdata['sn_value']]);
                    LogUtil::addAdminLog($param);
                }

                $arr[0] = [
                    'app_package'=>$pdata['app_package'],
                    'is_lock'=>$param['is_lock'],
                    'is_network'=>$param['is_network'],
                    'is_upgrade'=>$param['is_upgrade'],
                    'address'=>$param['address'],
                    'visit'=>$param['visit'],
                ];

                $param['status'] = 1;
                $param['contentType'] = 23;
                $param['type'] = 2;
                $param['batch'] = array($pdata['sn_value']);
                $param['title'] = 'OK';
                $param['statusType'] = '小程序编辑应用';
                $arr = json_encode(array_values($arr),true);
                $jPush = LogUtil::addPushLog($param,$arr);
                if(in_array(200,$jPush)){

                    $param['remark'] = '小程序编辑应用';
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$pdata['sn_value']]);
                    LogUtil::addAdminLog($param);
                    return ToolUtil::returnJson(200,'成功');
                }
                DB::rollBack();
                return ToolUtil::returnJson(300,'设备不在线或没联网');
                
            }
            DB::rollBack();
            return ToolUtil::returnJson(300,'失败');
        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'网络拥堵，请稍后再试');
        }
    }


    /**
     * 获取应用安装列表
     * 
     * @param $param
     * @return false|string
     */
    public static function getInstallAppList($param){

        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$param['id']],['a.value','p.teacher_id']);
        if($parent['value']){

            if($parent['teacher_id']){
                $field = ['i.teacher_app_id','a.app_name','a.app_img'];
                $idata = AppInstallModel::queryWhereTeacher(['i.sn_value'=>$parent['value']],$field);

                $data = [];
                $isset = [];
                foreach ($idata as $key => $value) {
                    if(!in_array($value['teacher_app_id'],$isset)){
                        $isset[] = $value['teacher_app_id'];
                        $data[] = $value;
                    }
                }                

            }else{
                $field = ['i.parent_app_id','a.app_name','a.app_img'];
                $idata = AppInstallModel::queryWhere(['i.sn_value'=>$parent['value']],$field);

                $data = [];
                $isset = [];
                foreach ($idata as $key => $value) {
                    if(!in_array($value['parent_app_id'],$isset)){
                        $isset[] = $value['parent_app_id'];
                        $data[] = $value;
                    }
                }
            }
            
            if(count($data)){
                return ToolUtil::returnJson(200,'成功',$data);
            }
            return ToolUtil::returnJson(400,'没有数据');
        }
        return ToolUtil::returnJson(301,'没有该设备信息');
    }


    /**
     * 获取家长应用
     * @param $param
     * @return false|string
     */
    public static function queryParentApp($param){

        $sn_id = (int)$param['snId'];
        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$sn_id],['value']);
        if(empty($parent['value'])){
            return ToolUtil::returnJson(400,'设备错误');
        }

        $field = ['p.id','p.app_name','p.app_img','a.name as snName','app_version_name','is_silent'];
        $data = ParentAppModel::queryLeftGet(['p.sn_value'=>$parent['value']],$field);

        if(count($data)){
            $result = self::handleInstall($data,$parent['value']);
            return ToolUtil::returnJson(200,'成功',$result);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    private static function handleInstall($data,$sn){
        foreach ($data as $k=>$v){
            $install = AppInstallModel::queryFirst(['sn_value'=>$sn,'parent_app_id'=>$v['id']],['id','lastUpdateTime']);
            if(!empty($install)){
                $v['install'] = 1;
                $v['install_time'] = $install['lastUpdateTime'];
            }else{
                $v['install'] = 0;
                $v['install_time'] = 0;
            }
            
            $data[$k] = $v;
        }
        return $data;
    }


    /**
     * 修改app静默状态
     * @param $param
     * @return false|string
     */
    public static function editAppSilent($param){

        $sn_id = (int)$param['snId'];
        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$sn_id],['value']);
        if(empty($parent['value'])){
            return ToolUtil::returnJson(400,'设备错误');
        }

        $pdata = ParentAppModel::queryFirst(['id'=>$param['appId']],['sn_value','app_package']);
        if(empty($pdata)){
            return ToolUtil::returnJson(400,'应用错误');
        }

        if(ParentAppModel::edit(['id'=>$param['appId']],['is_silent'=>0,'update_time'=>time()])){

            $param['remark'] = '修改应用为非静默状态';
            $param['type'] = 2;
            $param['batch'] = array($parent['value']);
            $param['contentType'] = 9;
            $param['statusType'] = '修改应用为非静默状态';
            $jPush = LogUtil::addPushLog($param,['package'=>$pdata['app_package']]);
            if(in_array(200,$jPush)){
                
                $param['details'] = ToolUtil::handleSuccessOrError(['code'=>'success','package'=>$pdata['app_package']]);
                LogUtil::addAdminLog($param);
                return ToolUtil::returnJson(200,'成功');
            }else{
                $param['details'] = ToolUtil::handleSuccessOrError(['code'=>'error','package'=>$pdata['app_package']],0);
                LogUtil::addAdminLog($param);
                return ToolUtil::returnJson(301,'推送失败');
            }

        }
        return ToolUtil::returnJson(300,'失败');
    }    


    /**
     * 删除上传应用
     * @param $param
     * @return false|string
     */
    public static function deleteParent($param){

        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$param['snId']],['a.id','a.value','p.teacher_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(301,'该设备没有绑定');
        }
        if($parent['teacher_id']){
            return ToolUtil::returnJson(302,'该设备已授权老师');
        }
        
        DB::beginTransaction();
        $app = ParentAppModel::queryFirst(['id'=>$param['appId']],['app_package']);
        if(ParentAppModel::delete(['id'=>$param['appId']])){

            $admin = AdminModel::queryFirst(['id'=>$param['userId']],['apk_num']);
            $apk_num = $admin['apk_num']-1;
            if($apk_num < 0){
                $apk_num = 0;
            }
            AdminModel::edit(['id'=>$param['userId']],['apk_num'=>$apk_num]);
            $param['status'] = 1;
            $param['contentType'] = 10;
            $param['type'] = 2;
            $param['batch'] = array($parent['value']);
            $param['title'] = 'OK';
            $param['statusType'] = '删除应用';
            $param['remark'] = "删除应用";
            $jPush = LogUtil::addPushLog($param,$app);
            $param['details']=ToolUtil::handleSuccessOrError(['appPackage'=>$app['app_package'],'sn'=>$parent['value']]);
            if(in_array(200,$jPush)){
                LogUtil::addAdminLog($param);
                DB::commit();
                $t_app_inside = DB::table('t_app_inside')->where('app_id',$param['appId'])->where('type',1)->delete();
                if($t_app_inside){
                    $param['contentType'] = 7;
                    $param['type'] = 2;
                    $param['batch'] = array($parent['value']);
                    $param['statusType'] = '小程序删除应用ID管控';
                    LogUtil::addPushLog($param);
                    $param['remark'] = '小程序删除应用ID管控';
                    $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$parent['value']]);
                    LogUtil::addAdminLog($param);    
                }

                return ToolUtil::returnJson(200,'成功');
            }
            DB::rollBack();
            return ToolUtil::returnJson(300,'设备不在线或没联网');
        }
        return ToolUtil::returnJson(300,'失败');
    }


    /**
     * 清除应用缓存
     * @param $param 应用id
     * @return false|string
     */
    public static function cleanAppCache($param){

        $id = (int)$param['id'];

        $pdata = ParentAppModel::queryFirst(['id'=>$id],['sn_value','app_package']);

        if(!$pdata){
            return ToolUtil::returnJson(301,'没有记录');
        }

        $parent = ParentSnModel::queryWhereFirst(['a.value'=>$pdata['sn_value']],['p.teacher_id','p.admin_id']);
        if(!$parent){
            return ToolUtil::returnJson(302,'该设备没有绑定');
        }
        if(!empty($parent['teacher_id'])){
            return ToolUtil::returnJson(303,'该设备授权老师，不能进行该操作');
        }

        $param['remark'] = "清除应用缓存";
        $param['userId'] = $parent['admin_id'];
        $param['lastIp'] = ToolUtil::get_real_ip();
        $param['status'] = 1;
        $param['contentType'] = 34;
        $param['type'] = 2;
        $param['batch'] = array($pdata['sn_value']);
        $param['title'] = 'OK';
        $param['statusType'] = '清除应用缓存';
        $jPush = LogUtil::addPushLog($param,['package'=>$pdata['app_package']]);
        $param['details']=ToolUtil::handleSuccessOrError(['appPackage'=>$pdata['app_package'],'sn'=>$pdata['sn_value']]);
        if(in_array(200,$jPush)){
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(200,'成功');
        }
        
        return ToolUtil::returnJson(300,'设备不在线或没联网');

    }

    /**
     * 更新应用白名单
     * @param $param
     * @return false|string
     */
    public static function whiteAppUpdate($param){

        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$param['snId']],['a.id','a.value','p.teacher_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(301,'该设备没有绑定');
        }
        if($parent['teacher_id']){
            return ToolUtil::returnJson(302,'该设备已授权老师');
        }

        if(empty($param['package'])){
            return ToolUtil::returnJson(401,'包名信息不存在');
        }
        $val = $param['package'];

        $white_app = DB::table('t_white_app')->where('sn',$parent['value'])->first(['batch_id','package_name','admin_id','sn','group']);

        try{

            if(empty($white_app)){
                $str = '添加应用白名单';
            }else{
                $str = '编辑应用白名单';
            }

            $logArr['userId'] = (int)$param['userId'];
            $logArr['remark'] = $str;
            
            $push_param['statusType'] = $str;
            $push_param['title'] = 'OK';
            $push_param['batch'] = array($parent['value']);
            $push_param['status'] = 1;
            $push_param['contentType'] = 46;
            $push_param['userId'] = (int)$param['userId'];
            $push_param['type'] = 2;
            $push_data = ['package_name'=>$val];
            $jPush = LogUtil::addPushLog($push_param,$push_data);
            if(in_array(200,$jPush)){

                $data = [
                    'batch_id'=>'',
                    'sn'=>$parent['value'],
                    'package_name'=>$val,
                ];

                if(empty($white_app)){
                    $data['group'] = 4;
                    $data['admin_id'] = (int)$param['userId'];
                    $data['create_time'] = time();
                    $res = DB::table('t_white_app')->insert($data);
                }else{
                    $data['update_time'] = time();
                    $res = DB::table('t_white_app')->where('sn',$parent['value'])->update($data);
                }
                
                if($res){
                    $logArr['details'] = '成功';
                    LogUtil::addAdminLog($logArr);
                    return ToolUtil::returnJson(200,'成功');
                }else{
                    $logArr['details'] = '失败';
                    LogUtil::addAdminLog($logArr);
                    return ToolUtil::returnJson(300,'失败');
                }

            }else{
                $logArr['details'] = '推送失败';
                LogUtil::addAdminLog($logArr);
                return ToolUtil::returnJson(300,'推送失败');
            }

        }catch (\Exception $exception){
            return ToolUtil::returnJson(500,'设置出错');
        }

    }


    /**
     * sn编号查询应用白名单
     * @param $param
     * @return false|string
     */
    public static function whiteAppBySnId($param){

        $parent = ParentSnModel::queryWhereFirst(['p.id'=>$param['snId']],['a.id','a.value','p.teacher_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(301,'该设备没有绑定');
        }
        if($parent['teacher_id']){
            return ToolUtil::returnJson(302,'该设备已授权老师');
        }

        $field = ['w.id','w.package_name','w.batch_id','w.sn','w.group'];
        $data = DB::table('t_white_app as w')->where('w.sn',$parent['value'])->first($field);
        if($data){
            $data['type'] = 1;
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');

    }


}